#include <windows.h>
#include <stdio.h>

#include "m3u8_file.h"

int test_m3u8()
{
    const char* url = "https://rscdn.ajmide.com/r_2429/2429.m3u8"; // Example M3U8 URL
//    const char* url = "https://brtv-radiolive.rbc.cn/alive/fm876.m3u8"; // Another optional M3U8 URL

    // 打开 M3U8 文件
    M3U8File* file = m3u8_fopen(url);
    if (file == NULL) {
        fprintf(stderr, "Unable to open M3U8 file: %s\n", url);
        return 1;
    }

    // 打开输出文件，将 TS 数据写入 output.ts 文件中
    FILE *outputFile = fopen("output.ts", "wb");
    if (outputFile == NULL) {
        fprintf(stderr, "Failed to open output file.\n");
        m3u8_fclose(file);
        return 1;
    }

    // 创建缓冲区读取 TS 文件内容
    size_t bufferSize = 188; // 188 字节，通常是 TS packet 大小
    char* buffer = (char*)malloc(bufferSize);
    if (buffer == NULL) {
        fprintf(stderr, "Memory allocation failed\n");
        m3u8_fclose(file);
        fclose(outputFile); // 确保关闭输出文件
        return 1;
    }

    // 循环读取 TS 文件内容
    size_t totalBytesRead = 0; // 记录读取的总字节数
    size_t bytesRead;

    // 读取 1MB 的 TS 数据
    while (totalBytesRead < 1 * 1024 * 1024) {
        bytesRead = m3u8_fread(buffer, 1, bufferSize, file);

        if (bytesRead > 0) {
            // 输出读取的字节数
            printf("Read %zu bytes of data\n", bytesRead);
            totalBytesRead += bytesRead;

            // 将读取到的数据写入输出文件
            size_t bytesWritten = fwrite(buffer, 1, bytesRead, outputFile);
            if (bytesWritten != bytesRead) {
                fprintf(stderr, "Error occurred while writing data.\n");
                break;
            }
        }
        else {
            // 读取过程中发生错误
            fprintf(stderr, "Error occurred while reading data.\n");
            break;
        }
    }

    // 检查是否读取到了数据
    if (totalBytesRead == 0) {
        fprintf(stderr, "No data was read.\n");
    } else {
        printf("Total %zu bytes of data read.\n", totalBytesRead);
    }

    // 清理内存并关闭文件
    free(buffer);
    m3u8_fclose(file);
    fclose(outputFile); // 关闭输出文件

    return 0;
}
